package com.dhecp.project.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.project.system.domain.SysRoleInfo;
import com.dhecp.project.system.mapper.SysRoleInfoMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysRoleInfoService;

/**
 * 角色信息服务层
 * @author DH-Xxj
 * @version 2019年10月18日
 */
@Service
public class SysRoleInfoServiceImpl implements SysRoleInfoService {

    private static final Logger log = LoggerFactory.getLogger(SysRoleInfoServiceImpl.class);
    
    @Autowired
    private SysRoleInfoMapper roleInfoMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

	/**
	 * 按条件查询角色信息
	 * @param params
	 * @return List-SysRoleInfo
	 * @throws Exception
	 * @author DH-Xxj
	 */
    @Override
    public List<SysRoleInfo> queryRoleInfoList(Map<String, Object> params) throws Exception {
//        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));		//常规查询条件SQL语句
//        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));		//数据权限查询条件SQL语句
        PageUtils.startPage();
        return roleInfoMapper.findRoleList(params);
    }

	/**
	 * 查询指定用户的角色列表
	 * @param userId 必要参数：用户编号
	 * @return HashSet-String
	 * @author DH-Xxj
	 */
    @Override
    public Set<String> queryRoleInfoListByUserIdToString(String userId){
    	Set<String> roles = new HashSet<String>();
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("userId", userId);
    	List<SysRoleInfo> sysRoleInfoList = roleInfoMapper.findRoleListByUserId(params);
    	for (SysRoleInfo sysRoleInfo: sysRoleInfoList){
    		if ("".equals(sysRoleInfo.getRoleName())){
    			roles.add(sysRoleInfo.getRoleName());
    		}
    	}
    	return roles;
    }

    /**
     * 查询所有有效的角色，以Map数组形式返回（分配用户角色）
     * @param params
     * @return List - Map 
     * @author DH-Xxj
     */
    @Override
    public List<Map<String,String>> queryRoleToMapList(Map<String, Object> params){
    	params.remove(DataFiltering.DATA_WHERE);
    	params.put(DataFiltering.DATA_WHERE, "deleted = 0");
    	List<SysRoleInfo> roleInfoList = roleInfoMapper.findRoleList(params);
    	List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
    	for (SysRoleInfo roleInfo : roleInfoList){
        	Map<String,String> roleMap = new LinkedHashMap<String,String>();
    		roleMap.put("value", roleInfo.getGuid().toString());
    		roleMap.put("title", roleInfo.getRoleName().toString());
    		listMap.add(roleMap);
    	}    	
    	return listMap;
    }
    
    /**
     * 查询用户已分配的有效角色列表，并返回Guid数组（分配用户角色）
     * @param params
     * @return List- String
     * @author DH-Xxj
     */
    @Override
    public List<String> queryUserBindRoleList(Map<String, Object> params){
    	params.remove(DataFiltering.DATA_WHERE);
    	List<SysRoleInfo> roleInfoList = roleInfoMapper.findRoleListByUserId(params);
    	List<String> listRole = new ArrayList<String>();
    	for (SysRoleInfo roleInfo : roleInfoList){
    		listRole.add(roleInfo.getGuid().toString());
    	}    	
    	return listRole;
    }
    
	/**
	 * 查询指定用户未分配的角色列表
	 * @param userId 必要参数：用户编号
	 * @return List-SysRoleInfo
	 * @throws Exception
	 * @author DH-Xxj
	 */
    @Override
    public List<SysRoleInfo> queryLackRoleListByUserId(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));		//常规查询条件SQL语句
        PageUtils.startPage();
        return roleInfoMapper.findLackRoleListByUserId(params);
    }
    
	/**
	 * 查询指定用户已分配的角色列表
	 * @param userId 必要参数：用户编号
	 * @return List-SysRoleInfo
	 * @author DH-Xxj
	 */
    @Override
    public List<SysRoleInfo> queryRoleInfoListByUserId(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));		//常规查询条件SQL语句
    	PageUtils.startPage();
    	return roleInfoMapper.findRoleListByUserId(params);
    }

    /**
     * 新增角色
     * @param roleInfoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertRoleInfo(Map<String, Object> params) {
        List<SysRoleInfo> roleInfoList = JSON.parseArray(params.get("roleInfoItems").toString(), SysRoleInfo.class);
        if (roleInfoList == null || roleInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysRoleInfo roleInfo : roleInfoList) {
            if (roleInfoMapper.findRoleByRoleName(roleInfo.getRoleName()) != null){
                return AjaxResult.error("[" + roleInfo.getRoleName() + "]已经存在，不能重复添加！");
            }else{
            	roleInfo.setCreateUser(ShiroUtils.getUserId());
            	roleInfo.setCreateTime(new Date());
            	roleInfo.setUpdateUser(ShiroUtils.getUserId());
            	roleInfo.setUpdateTime(new Date());
            	roleInfoMapper.insert(roleInfo);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 通过guid删除角色
     * @param roleInfoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteRoleInfo(Map<String, Object> params) {
        List<SysRoleInfo> roleInfoList = JSON.parseArray(params.get("roleInfoItems").toString(), SysRoleInfo.class);
        if (roleInfoList == null || roleInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysRoleInfo roleInfo : roleInfoList) {
            if ("".equals(roleInfo.getGuid())){
                return AjaxResult.error("请选择要删除的角色！");
            }
            roleInfoMapper.deleteByGuid(roleInfo.getGuid());
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改角色信息
     * @param roleInfoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateRoleInfo(Map<String, Object> params) {
        List<SysRoleInfo> roleInfoList = JSON.parseArray(params.get("roleInfoItems").toString(), SysRoleInfo.class);
        if (roleInfoList == null || roleInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysRoleInfo roleInfo : roleInfoList) {
            if ("".equals(roleInfo.getGuid())){
                return AjaxResult.error("请选择要修改的角色！");
            }
            roleInfo.setUpdateUser(ShiroUtils.getUserId());
            roleInfo.setUpdateTime(new Date());
            roleInfoMapper.update(roleInfo);
        }
        return AjaxResult.success("操作成功");
    }
    /**
     * 查询指定用户已分配的角色列表
     * @param roleName 必要参数：角色名称
     * @return SysRoleInfo
     * @author DH-Xxj
     */
    @Override
    public SysRoleInfo findRoleByRoleName(String roleName){
        return roleInfoMapper.findRoleByRoleName(roleName);
    }
    
}
